import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;

public class Driver {

	static int MAX_GENS = 75;
	static int STAGNATION = 10000;
	static double MIN_FITNESS = -0.4;

	public static void main(String[] args){
		Random rand = new Random();
		StringBuffer buffer = new StringBuffer("");

		Population pop = new Population(1000, 5, true,rand);
		int gen = 0;
		int stallCount = 0;
		double bestFitness = Double.MAX_VALUE;
		String winningEquation = " ";
		int lastImprovement = -1;
		double newBest = Double.MAX_VALUE;
		Object[] results = null;

		long start = System.nanoTime();

		while(gen<MAX_GENS && bestFitness > MIN_FITNESS){
			//			System.out.println("======\n\n" + pop.oldGen.get(0).root.size + "\n\n======\n\n");

			results = pop.doGeneration();
			newBest = (Double)results[0];
			gen++;
			stallCount++;
			if(newBest<bestFitness){
				bestFitness = newBest;
				winningEquation = (String)results[1];
				lastImprovement = gen-1;
				stallCount = 0;
			}else if(newBest>bestFitness){
				stallCount = 0;
			}
			buffer.append("Gen: " + gen + ": \n");
			buffer.append("\tBest Fit: " + newBest + "\n");
			buffer.append("\tBest Size: " + (Integer)results[2]);
			buffer.append(" (" + (Double)results[4] + ")\n");
			//			System.out.println("Gen "+gen+": ");
			//			System.out.println("\tBest Fit: " + newBest);
			//			System.out.println(" (" + (double)results[3] + ")");
			//			System.out.print("\tBest Size: " + (int)results[2]);
			//			System.out.println(" (" + (double)results[4] + ")");
		}

		long end = System.nanoTime();

		buffer.append("\nTime elapsed for this run: " + (end-start) / Math.pow(10, 9) + " sec\n\n");
		buffer.append("Best: \n");
		buffer.append(winningEquation);

		System.out.println(buffer.toString());
		
		try {
			FileWriter f = new FileWriter("Result.txt");
			f.write(buffer.toString());
			f.close();
		} catch (IOException e) {

		}

	}

}
